package viv.karaoke.book;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;

public class SongFragment extends Fragment
{
	private SongDataSource datasource;
	private List<song> myListItems;
	private SongAdapter sAdapter;
	private boolean loadingMore = false;
	private int itemsPerPage = 12;	
	private String mQuery = "";	
	private ListView lvSong;
	private MainActivity activity;
	
	@Override
	public View onCreateView( LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState )
	{
		View view = inflater.inflate(R.layout.song_search, container, false);
		
		lvSong =  (ListView) view.findViewById(R.id.lvSearch);
		
		return view;
	}
	
//	@Override
//	public View onResume( LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
//	{
//		View view = inflater.inflate(R.layout.song_search, container, false);
//		
//		lvSong =  (ListView) view.findViewById(R.id.lvSearch);
//		
//		return view;
//	}
	
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
	    super.onActivityCreated(savedInstanceState);
	    
	    activity = (MainActivity)getActivity();
	    
	    if (activity != null) {
	    	//Get data to list of song
	  		datasource = new SongDataSource(activity);
	  	    datasource.open();
	  	  
		    mQuery = activity.mQuery;
		    try
		    {
		  	    myListItems = datasource.getAllSongs(mQuery, 0);
	
		  	    if(myListItems.size() > 0)
		  	    {
		  	    	sAdapter = new SongAdapter(activity, myListItems);	        
		  	    	lvSong.setAdapter(sAdapter);
		  	    
			    //Here is where the magic happens
			    lvSong.setOnScrollListener(new OnScrollListener(){
			    
			    //Useless here, skip!
			    @Override
			    public void onScrollStateChanged(AbsListView view, int scrollState) {
			    	
			    }
	
			 	@Override
			    public void onScroll(AbsListView view, int firstVisibleItem,
			    		int visibleItemCount, int totalItemCount) {
	
			    		//what is the bottom item that is visible
			    		int lastInScreen = firstVisibleItem + visibleItemCount;				
	
			    		//is the bottom item visible & not loading more already ? Load more !
			    		if((lastInScreen == totalItemCount) && !(loadingMore)){
			    			Thread thread =  new Thread(null, loadMoreListItems);
			    			thread.start();
			    		}
			    	}
			    });    	    			    

		  	  }
		    }
		    catch(Exception ex)
		    {
		    	
		    }
	    }
	}
	
	//Runnable to load the items 
    private Runnable loadMoreListItems = new Runnable() {			
		@Override
		public void run() {
			//Set flag so we can't load new items 2 at the same time
			loadingMore = true;
			
			//Reset the array that holds the new items
			//myListItems = new List<song>();
			int count = myListItems.size();			
			long last = myListItems.get(count-1).getSongId();
			
			myListItems = new List<song>() {
				
				@Override
				public <T> T[] toArray(T[] array) {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public Object[] toArray() {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public List<song> subList(int start, int end) {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public int size() {
					// TODO Auto-generated method stub
					return 0;
				}
				
				@Override
				public song set(int location, song object) {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public boolean retainAll(Collection<?> arg0) {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public boolean removeAll(Collection<?> arg0) {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public boolean remove(Object object) {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public song remove(int location) {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public ListIterator<song> listIterator(int location) {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public ListIterator<song> listIterator() {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public int lastIndexOf(Object object) {
					// TODO Auto-generated method stub
					return 0;
				}
				
				@Override
				public Iterator<song> iterator() {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public boolean isEmpty() {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public int indexOf(Object object) {
					// TODO Auto-generated method stub
					return 0;
				}
				
				@Override
				public song get(int location) {
					// TODO Auto-generated method stub
					return null;
				}
				
				@Override
				public boolean containsAll(Collection<?> arg0) {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public boolean contains(Object object) {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public void clear() {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public boolean addAll(int arg0, Collection<? extends song> arg1) {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public boolean addAll(Collection<? extends song> arg0) {
					// TODO Auto-generated method stub
					return false;
				}
				
				@Override
				public void add(int location, song object) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public boolean add(song object) {
					// TODO Auto-generated method stub
					return false;
				}
			};
	    	
			//Simulate a delay, delete this on a production environment!
//	    	try { Thread.sleep(1000);
//			} catch (InterruptedException e) {}
			
			//Get 15 new list items
	    	myListItems = datasource.getMoreSongs(mQuery, last);
			
	    	//Done! now continue on the UI thread
	    	activity.runOnUiThread(returnRes);	    	
		}
	};	
	
    
	//Since we can't update our UI from a thread this Runnable takes care of that! 
    private Runnable returnRes = new Runnable() {
        @Override
        public void run() {
        	
			//Loop thru the new items and add them to the adapter
			if(myListItems != null && myListItems.size() > 0){
                for(int i=0;i<myListItems.size();i++)
                	sAdapter.add(myListItems.get(i));
            }
        				
			//Tell to the adapter that changes have been made, this will cause the list to refresh
            sAdapter.notifyDataSetChanged();
			
			//Done loading more.
            if(myListItems.size() >= itemsPerPage){
            	loadingMore = false;
            }
        }
    };	
}
